package com.bauer.java.drools.demo;

import com.bauer.java.drools.KieModuleModelExample;
import com.bauer.java.drools.param.RuleParam;
import com.bauer.java.drools.result.RuleResult;
import org.apache.commons.io.IOUtils;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message.Level;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.ObjectFilter;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author ：rui.wei
 * @Date ：Created in 15:51 2019/8/9
 * @Description：
 */
public class DynamicGenDrlDemo {


    public static void main(String[] args) throws Exception {
        KieServices kieServices = KieServices.Factory.get();
        KieModuleModel kieModuleModel = kieServices.newKieModuleModel();
        kieModuleModel.newKieBaseModel("xx").newKieSessionModel("xxxxx");

        KieFileSystem kfs = kieServices.newKieFileSystem();

        //拼接模板 生成drl文件
        String ruleTemplate = IOUtils
                .toString(KieModuleModelExample.class.getResourceAsStream("/template.drl"), "UTF-8");
        String code = MessageFormat
                .format(ruleTemplate, "package1", "ruleName", "this[\"age\"] >20", "ruleName", "ruleCode", "1.2");
        //
        kfs.write("src/main/resources/drools/hello.drl",code);
        kfs.writeKModuleXML(kieModuleModel.toXML());
        KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
        System.out.println(kieBuilder.getResults().getMessages(Level.ERROR).size());
        KieContainer kContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
        RuleParam ruleParam = new RuleParam();
        ruleParam.put("age",21);
        KieSession kieSession = kContainer.newKieSession("xxxxx");
        kieSession.insert(ruleParam);
        kieSession.fireAllRules();
        Collection c = kieSession.getObjects(new ObjectFilter() {
            public boolean accept(Object object) {
                if (object instanceof RuleResult) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        //获取触发的结果
        List<RuleResult> results = new ArrayList<>(c);

        kieSession.dispose();


    }

}
